package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author ydd
 * @since 2024-08-16
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private IServeItemService serveItemService;

    @Resource
    private IRegionService regionService;



    /**
     * 分页查询
     * @param servePageQueryReqDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //通过baseMapper调用queryServeListByRegionId方法
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                new PageHelperUtils.QueryExecutor<ServeResDTO>() {
                    @Override
                    public List<ServeResDTO> query() {
                        return baseMapper.queryServeListByRegionId
                                (servePageQueryReqDTO.getRegionId());
                    }
                });
    }



    /**
     * 给指定区域添加服务
     * @param dtoList 添加服务列表
     */
    @Override
    @Transactional
    public void addBatch(List<ServeUpsertReqDTO> dtoList) {
        // 判断dtoList是否为空
        if (dtoList == null || dtoList.isEmpty()) {
            throw new ForbiddenOperationException("添加的服务列表不能为空");
        }
        // 1、循环遍历dtoList集合，添加区域服务
        for (ServeUpsertReqDTO dto : dtoList) {
            // 2、判断服务项是否存在，且状态为启用
            ServeItem serveItem = serveItemService.getById(dto.getServeItemId());
            if (serveItem == null || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("服务项不存在或状态不正确");
            }
            // 3、判断同一个区域下的服务项是否重复添加
            Serve serve = this.lambdaQuery()
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .one();
            if (serve != null) {
                throw new ForbiddenOperationException("该区域下已存在该服务项【" + serveItem.getName() + "】");
            }
            // 4、添加服务项
            serve = BeanUtil.copyProperties(dto, Serve.class);
            boolean save = this.save(serve);
            if (!save) {
                throw new ForbiddenOperationException("添加服务失败");
            }

            Region region = regionService.getById(dto.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }



    /**
     * 区域服务价格修改
     * @param id 服务id
     * @param price 价格
     * @return 服务
     */
    @Override
    public Serve updatePrice(Long id, BigDecimal price) {
        // 修改服务价格
        boolean update = this.lambdaUpdate()
                .set(Serve::getPrice, price)
                .eq(Serve::getId, id)
                .update();
        if (!update) {
            throw new CommonException("修改服务价格失败");
        }
        return baseMapper.selectById(id);

    }


    /**
     * 区域服务上架
     * @param id 服务id
     */
    @Override
    public Serve  onSale(Long id) {
        // 查询服务
        Serve serve = this.getById(id);
        // 判断服务是否存在
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }

        // 判断服务当前状态是否是草稿或下架，当前状态不是草稿或下架，上架失败
        if (serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus()
                && serve.getSaleStatus() == FoundationStatusEnum.DISABLE.getStatus()) {
            throw new ForbiddenOperationException("服务不是草稿或下架");
        }

        // 查询服务项
        ServeItem serveItem = serveItemService.getById(serve.getServeItemId());
        // 判断服务项是否存在,如果不能存在，不能上架
        if (ObjectUtil.isNull(serveItem)) {
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        // 判断服务项是否启用，如果未启用，不能上架
        if (serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项未启用，不能上架");
        }

        // 更新上架状态
        boolean update = this.lambdaUpdate()
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .eq(Serve::getId, id)
                .update();
        if (!update) {
            throw new CommonException("启动服务失败");
        }

        return baseMapper.selectById(id);
    }


}
